package com.cucn.eduservice.controller;


import com.cucn.commonutils.Result;
import com.cucn.commonutils.ResultCode;
import com.cucn.eduservice.client.VodClient;
import com.cucn.eduservice.entity.EduVideo;
import com.cucn.eduservice.service.EduVideoService;
import com.cucn.servicebase.exceptionhandler.GuliException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 * 课程视频 前端控制器
 * </p>
 *
 * @author KouChaoJie
 * @since 2021-09-29
 */
//@CrossOrigin
@RestController
@RequestMapping("/eduservice/video")
public class EduVideoController {
    @Autowired
    private EduVideoService videoService;

    /**
     * 注入vodClient
     */
    @Autowired
    private VodClient vodClient;

    /**
     * 添加小节
     *
     * @param eduVideo 要添加的小节信息对象
     */
    @PostMapping("/addVideo")
    public Result addVideo(@RequestBody EduVideo eduVideo) {
        videoService.save(eduVideo);
        return Result.ok();
    }

    /**
     * 删除小节,删除对应阿里云视频
     *
     * @param id 需要删除的小节的id
     */
    @DeleteMapping("{id}")
    public Result deleteVideo(@PathVariable String id) {
        //根据小节id获得视频id,再删除视频
        EduVideo eduVideo = videoService.getById(id);
        String videoSourceId = eduVideo.getVideoSourceId();
        if (!StringUtils.isEmpty(videoSourceId)) {
            Result result = vodClient.removeAlyVideo(videoSourceId);
            if (result.getCode().equals(ResultCode.ERROR)) {
                throw new GuliException(ResultCode.ERROR, "删除视频失败,熔断器...");
            }
        }

        videoService.removeById(id);

        return Result.ok();
    }

    /**
     * 根据id查询小节信息做修改数据回显
     */
    @GetMapping("/getVideoInfo/{videoId}")
    public Result getVideoInfo(@PathVariable String videoId) {
        EduVideo video = videoService.getById(videoId);

        return Result.ok().data("video", video);
    }

    //KouTODO:2021/9/30 21:01 Kou 修改小节

    /**
     * @param eduVideo 修改的小节信息
     * @return Result修改成功信息
     */
    @PostMapping("/updateVideo")
    public Result updateVideo(@RequestBody EduVideo eduVideo) {
        videoService.updateById(eduVideo);
        return Result.ok();
    }
}

